package com.donger.auth.validate;

import cn.hutool.core.util.StrUtil;
import com.donger.auth.config.FilterIgnorePropertiesConfig;
import com.donger.auth.exception.ValidateCodeException;
import com.donger.auth.utils.AuthUtils;
import com.donger.common.core.constant.CommonConstants;
import com.donger.common.core.constant.SecurityConstants;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * @author aeizzz
 * 检验图片验证码
 */

@Slf4j
@AllArgsConstructor
@Component(value = SecurityConstants.DEFAULT_PARAMETER_NAME_CODE_IMAGE)
public class ImagesValidateCodeProcessor implements ValidateCodeProcessor {


    @Autowired
    private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig;

    private final RedisTemplate redisTemplate;

    @SneakyThrows
    @Override
    public void validate(HttpServletRequest request) {

        if(!"password".equals(request.getParameter("grant_type"))){
            // 不是密码模式直接通过
            return;
        }

        String[] strings = AuthUtils.extractAndDecodeHeader(request);
        List<String> clients = filterIgnorePropertiesConfig.getClients();
        if (filterIgnorePropertiesConfig.getClients().contains(strings[0])) {
            // 校验通过 直接返回
            return;
        }

        log.debug("校验图片验证码 -> {}", request.getRequestURI());
        String uuid = request.getParameter("uuid");
        String code = request.getParameter("code");
        log.debug("获取参数 uuid -> {},code -> {}", uuid, code);

        if (StrUtil.isBlank(code)) {
            throw new ValidateCodeException("验证码不能为空");
        }
        if (StrUtil.isBlank(uuid)) {
            throw new ValidateCodeException("参数校验出错，请刷新后重试");
        }

        String captcha = (String) redisTemplate.opsForValue().get(CommonConstants.DEFAULT_CAPTCHA_KEY + uuid);
        log.debug("获取redis 中的 验证码 -> {}", captcha);

        if (!code.equalsIgnoreCase(captcha)) {
            redisTemplate.delete(CommonConstants.DEFAULT_CAPTCHA_KEY + uuid);
            throw new ValidateCodeException("验证码输入错误");
        }
    }
}
